#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import winreg
import tkinter as tk
from concurrent.futures import ThreadPoolExecutor
from tkinter import messagebox
from tkinter.filedialog import askdirectory

from config import window

class Application(tk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.master = master
        self.pack(pady=30)
        self.create_widgets()
        self.style_widgets()

    def create_widgets(self):
        """
        创建组件
        :return:
        """
        self.btn_sel_dir = tk.Button(self, text="点击选择文件夹", command=self.sel_dir)
        self.btn_sel_dir.pack(pady=5)
        self.var_dir = tk.StringVar()
        self.var_dir.set('请选择文件夹')
        self.input_show_dir = tk.Entry(self, textvariable=self.var_dir, state=tk.DISABLED)
        self.input_show_dir.pack(pady=5)
        self.btn_start = tk.Button(self, text='开始处理', command=self.start_handle)
        self.btn_start.pack(pady=15)
        self.var_done_count = tk.StringVar()
        self.show_done_lable = tk.Label(self, textvariable=self.var_done_count)
        self.show_done_lable.pack(pady=5)
        self.var_result = tk.StringVar()
        self.show_result_lable = tk.Label(self, textvariable=self.var_result)
        self.show_result_lable.pack(pady=15)

    def style_widgets(self):
        """
        设置组件的样式
        :return:
        """
        btn_style = {
            'font': ('黑体', 15),
            'bg': '#337ab7',
            'fg': 'white',
            'width': 15,
            'relief': tk.FLAT
        }
        self.config(bg='white')
        self.btn_sel_dir.config(**btn_style)
        self.input_show_dir.config(width=50, relief=tk.SOLID)
        self.btn_start.config(**btn_style)
        self.show_done_lable.config(bg='white', fg='black', font=('黑体', 15))
        self.show_result_lable.config(bg='white', fg='green', font=('黑体', 15))

    def sel_dir(self):
        dir_name = askdirectory(title='请选择文件夹')
        self.var_dir.set(dir_name)

    @staticmethod
    def get_desktop():
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                             r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders', )
        return winreg.QueryValueEx(key, "Desktop")[0]

    def compose(self, dirpath, output_dir):
        """
        将音频与视频合并成一个文件
        :param dirpath:目标目录路径
        :param output_dir:输出路径
        :return:
        """
        done_count = 0
        dirname = dirpath.split('/')[-1]
        output_dir = '{}/{}合并结果'.format(output_dir, dirname)
        dir_list_name = list(set([i.split('.')[0] for i in os.listdir(dirpath)]))
        if not os.path.exists(output_dir):
            os.mkdir(output_dir)

        def com(name, sum_count):
            nonlocal done_count
            video_path = "{}/{}.mp4".format(dirpath, name)
            audio_path = "{}/{}.mp3".format(dirpath, name)
            result_path = '{}/{}.mp4'.format(output_dir, name)
            os.system('ffmpeg -i "{}" -i "{}" -c copy "{}" -loglevel quiet'.format(video_path, audio_path, result_path))
            self.var_result.set(f'{name}:处理完成！')
            done_count += 1
            self.var_done_count.set(f'完成数：{done_count}/总数：{sum_count}')
            if done_count == sum_count:
                self.var_result.set('全部处理完成！')

        p = ThreadPoolExecutor(10)
        for name in dir_list_name:
            p.submit(com, name, len(dir_list_name, ))

    def start_handle(self):
        dirpath = self.var_dir.get()
        if dirpath == '请选择文件夹':
            messagebox.showwarning(title='导入失败', message='未导入文件夹')
        else:
            output_dir = askdirectory(title="请选择输出目录", initialdir=self.get_desktop())
            self.compose(dirpath, output_dir)

if __name__ == '__main__':
    app = Application(master=window)
    window.mainloop()
